package com.edianping.search;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.edianping.sphinx.SphinxClient;
import com.edianping.sphinx.SphinxException;
import com.edianping.sphinx.SphinxMatch;
import com.edianping.sphinx.SphinxResult;

public class ReviewSearchManager {
	SphinxClient client;
	String index = "review_index,review_stemmed";
	
	protected static Logger log = Logger.getLogger(ReviewSearchManager.class);
	
	public ReviewSearchManager( String host, int port ){
		int mode = SphinxClient.SPH_MATCH_ALL;
		int offset = 0;
		int limit = 20;
		int sortMode = SphinxClient.SPH_SORT_RELEVANCE;
		String sortClause = "";
		
		client = new SphinxClient();
		
		try {
			client.SetServer ( host, port );
			client.SetWeights ( new int[] { 100, 1 } );
			client.SetMatchMode ( mode );
			client.SetLimits ( offset, limit );
			client.SetSortMode ( sortMode, sortClause );
		} catch (SphinxException e) {
			log.error( "Review Search Manager setup error" );
		}
	}
	
	public List<Integer> SearchReviewByProductId( String keyword, int productId ) throws SphinxException {
		List<Integer> result = new ArrayList<Integer>();
		
		int[] value = {productId};
		client.SetFilter( "product_id_list", value, false);
		
		
		SphinxResult res = client.Query(keyword, this.index );
		if ( res == null )
		{
			log.error( "Search Error: " + client.GetLastError() );
		}
		if ( client.GetLastWarning()!=null && client.GetLastWarning().length()>0 ){
			log.warn( "Search WARNING: " + client.GetLastWarning() );
		}
		
		//assemble result
		for ( int i=0; i<res.matches.length; i++ )
		{
			SphinxMatch info = res.matches[i];
			result.add( (int)info.docId );
		}
		
		return result;
	}
}
